package stage1.module4.Q2;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        final String FLAG = "end";

        ArrayList<String> dict = new ArrayList<>();
        Scanner scanner = new Scanner(System.in);

        // 获取用户输入数据
        String inp;
        do {
            System.out.println("请输入: ");
            inp = scanner.nextLine();
            dict.add(inp);
        } while (!inp.equals(FLAG));

        String[] dictArr = dict.toArray(new String[0]);

        System.out.println("排序前: " + Arrays.toString(dictArr));

        // 排序
        Arrays.sort(dictArr, (o1, o2) -> -o1.compareToIgnoreCase(o2));

        System.out.println("排序后: " + Arrays.toString(dictArr));

        final String FILE_NAME = "./src/stage1/module4/Q2/abc.txt";

        // 数据写入文件
        FileWriter fw = null;
        try {
            fw = new FileWriter(FILE_NAME);
            for (String s : dictArr) {
                try {
                    fw.write(s + "\n");
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if (fw != null) {
                try {
                    fw.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
